<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项 - Todo App</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto max-w-2xl px-4 py-8">
        <div class="bg-white rounded-lg shadow-lg p-6">
            <h1 class="text-3xl font-bold text-center text-gray-800 mb-6">待办事项</h1>
            
            <!-- 添加新待办 -->
            <div class="mb-6">
                <div class="flex gap-2">
                    <input 
                        type="text" 
                        id="newTodoInput"
                        placeholder="添加新的待办事项..."
                        class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        onkeypress="if(event.key === 'Enter') addTodo()"
                    >
                    <button 
                        onclick="addTodo()"
                        class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition duration-200"
                    >
                        <i class="fas fa-plus"></i> 添加
                    </button>
                </div>
            </div>

            <!-- 筛选按钮 -->
            <div class="flex gap-2 mb-4">
                <button 
                    onclick="setFilter('all')"
                    class="filter-btn px-3 py-1 rounded-full text-sm font-medium transition duration-200 bg-blue-500 text-white"
                    data-filter="all"
                >
                    全部
                </button>
                <button 
                    onclick="setFilter('active')"
                    class="filter-btn px-3 py-1 rounded-full text-sm font-medium transition duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    data-filter="active"
                >
                    未完成
                </button>
                <button 
                    onclick="setFilter('completed')"
                    class="filter-btn px-3 py-1 rounded-full text-sm font-medium transition duration-200 bg-gray-200 text-gray-700 hover:bg-gray-300"
                    data-filter="completed"
                >
                    已完成
                </button>
            </div>

            <!-- 待办列表 -->
            <div id="todoList" class="space-y-2">
                <!-- 待办事项将在这里动态生成 -->
            </div>

            <!-- 空状态 -->
            <div id="emptyState" class="text-center py-8 text-gray-500 hidden">
                <i class="fas fa-clipboard-list text-4xl mb-2"></i>
                <p>暂无待办事项</p>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center">
        <div class="bg-white rounded-lg p-6 w-96">
            <h3 class="text-lg font-semibold mb-4">编辑待办事项</h3>
            <input 
                type="text" 
                id="editTodoInput"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
            <div class="flex gap-2 mt-4 justify-end">
                <button 
                    onclick="closeEditModal()"
                    class="px-4 py-2 text-gray-600 hover:text-gray-800"
                >
                    取消
                </button>
                <button 
                    onclick="saveEdit()"
                    class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                >
                    保存
                </button>
            </div>
        </div>
    </div>

    <script>
        let todos = [];
        let currentFilter = 'all';
        let editingId = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadTodos();
        });

        // 加载待办事项
        async function loadTodos() {
            try {
                const response = await fetch('/api/todos');
                todos = await response.json();
                renderTodos();
            } catch (error) {
                console.error('加载待办事项失败:', error);
            }
        }

        // 渲染待办事项
        function renderTodos() {
            const todoList = document.getElementById('todoList');
            const emptyState = document.getElementById('emptyState');
            
            let filteredTodos = todos;
            if (currentFilter === 'active') {
                filteredTodos = todos.filter(todo => !todo.completed);
            } else if (currentFilter === 'completed') {
                filteredTodos = todos.filter(todo => todo.completed);
            }

            if (filteredTodos.length === 0) {
                todoList.innerHTML = '';
                emptyState.classList.remove('hidden');
                return;
            }

            emptyState.classList.add('hidden');
            todoList.innerHTML = filteredTodos.map(todo => `
                <div class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg hover:bg-gray-50">
                    <input 
                        type="checkbox" 
                        ${todo.completed ? 'checked' : ''}
                        onchange="toggleTodo(${todo.id})"
                        class="w-5 h-5 text-blue-500 rounded focus:ring-2 focus:ring-blue-500"
                    >
                    <span class="flex-1 ${todo.completed ? 'line-through text-gray-500' : 'text-gray-800'}">
                        ${todo.title}
                    </span>
                    <button 
                        onclick="openEditModal(${todo.id})"
                        class="text-blue-500 hover:text-blue-700"
                    >
                        <i class="fas fa-edit"></i>
                    </button>
                    <button 
                        onclick="deleteTodo(${todo.id})"
                        class="text-red-500 hover:text-red-700"
                    >
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `).join('');
        }

        // 添加待办事项
        async function addTodo() {
            const input = document.getElementById('newTodoInput');
            const title = input.value.trim();
            
            if (!title) return;

            try {
                const response = await fetch('/api/todos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ title }),
                });
                
                const newTodo = await response.json();
                todos.unshift(newTodo);
                renderTodos();
                input.value = '';
            } catch (error) {
                console.error('添加待办事项失败:', error);
            }
        }

        // 切换完成状态
        async function toggleTodo(id) {
            const todo = todos.find(t => t.id === id);
            if (!todo) return;

            try {
                await fetch(`/api/todos/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ completed: !todo.completed }),
                });
                
                todo.completed = !todo.completed;
                renderTodos();
            } catch (error) {
                console.error('更新待办事项失败:', error);
            }
        }

        // 删除待办事项
        async function deleteTodo(id) {
            if (!confirm('确定要删除这个待办事项吗？')) return;

            try {
                await fetch(`/api/todos/${id}`, {
                    method: 'DELETE',
                });
                
                todos = todos.filter(t => t.id !== id);
                renderTodos();
            } catch (error) {
                console.error('删除待办事项失败:', error);
            }
        }

        // 设置筛选
        function setFilter(filter) {
            currentFilter = filter;
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('bg-blue-500', 'text-white');
                btn.classList.add('bg-gray-200', 'text-gray-700');
            });
            document.querySelector(`[data-filter="${filter}"]`).classList.add('bg-blue-500', 'text-white');
            document.querySelector(`[data-filter="${filter}"]`).classList.remove('bg-gray-200', 'text-gray-700');
            renderTodos();
        }

        // 打开编辑模态框
        function openEditModal(id) {
            const todo = todos.find(t => t.id === id);
            if (!todo) return;

            editingId = id;
            document.getElementById('editTodoInput').value = todo.title;
            document.getElementById('editModal').classList.remove('hidden');
            document.getElementById('editModal').classList.add('flex');
        }

        // 关闭编辑模态框
        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
            document.getElementById('editModal').classList.remove('flex');
            editingId = null;
        }

        // 保存编辑
        async function saveEdit() {
            const input = document.getElementById('editTodoInput');
            const title = input.value.trim();
            
            if (!title || !editingId) return;

            try {
                await fetch(`/api/todos/${editingId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ title }),
                });
                
                const todo = todos.find(t => t.id === editingId);
                if (todo) {
                    todo.title = title;
                    renderTodos();
                }
                closeEditModal();
            } catch (error) {
                console.error('更新待办事项失败:', error);
            }
        }

        // 点击模态框外部关闭
        document.getElementById('editModal').addEventListener('click', (e) => {
            if (e.target.id === 'editModal') {
                closeEditModal();
            }
        });
    </script>
</body>
</html>
